<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :minHeight="100"
  >
    <div style="min-height: 100px; padding: 30px 0">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { FormSchema } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { getDepartment } from '/@/api/system/system';
  import { dateUtil as dayjs } from '/@/utils/dateUtil';
  import { getMessage_oaSetAgent } from '/@/api/email/email';

  export default defineComponent({
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      let isUpdate = ref(true);
      let dataRef = ref<Recordable>({});

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false, width: '30%' });
        isUpdate.value = !!data?.isUpdate;
        console.log('data', data);
        dataRef.value = data.record;
      });
      const FormSchema: FormSchema[] = [
        {
          field: 'agentDeptCode',
          label: '代理部门',
          component: 'ApiTreeSelect',
          defaultValue: '',
          required: true,
          colProps: {
            span: 22,
          },
          componentProps: {
            api: getDepartment,
            multiple: false,
            maxTagCount: 3,
            resultField: 'list',
            fieldNames: {
              label: 'name',
              key: 'code',
              value: 'code',
            },
            treeNodeFilterProp: 'name',
            treeDefaultExpandAll: true,
            getPopupContainer: () => document.body,
          },
        },
      ];
      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: FormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const getTitle = '设置代理部门';

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          const formData = Object.assign({}, dataRef.value, values);
          formData.agentDate = dayjs().format('YYYY-MM-DD');

          console.log('formData', formData);
          await getMessage_oaSetAgent(formData);
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerModal,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
